package com.xyazm.tms.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xyazm.common.utils.RandomUtil;
import com.xyazm.tms.dao.LogisticOrderDAO;
import com.xyazm.tms.domain.dto.SendOutDTO;
import com.xyazm.tms.domain.entity.LogisticOrderDO;
import com.xyazm.tms.domain.param.SendOutParam;
import com.xyazm.tms.enums.SendOutStatusEnum;
import com.xyazm.tms.exception.TmsBizException;
import com.xyazm.tms.mapstruct.TmsApiMapstruct;
import com.xyazm.tms.service.ITmsService;
import com.xyazm.wms.domain.dto.PlaceLogisticOrderDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class TmsServiceImpl implements ITmsService {


    @Autowired
    private LogisticOrderDAO logisticOrderDAO;


    @Override
    public SendOutDTO sendOut(SendOutParam param) {
        String tmsException = param.getTmsException();
        if(StringUtils.isNotBlank(tmsException) && tmsException.equals("true")) {
            throw new TmsBizException("发货异常！");
        }

        // 1.调用三方物流系统,下物流单子单
        PlaceLogisticOrderDTO placeLogisticOrderDTO = thirdPartyLogisticApi(param);

        // 2.生成物流单
        LogisticOrderDO logisticOrderDO = TmsApiMapstruct.INSTANCE.convertLogisticOrder(param);
        logisticOrderDO.setLogisticCode(placeLogisticOrderDTO.getLogisticCode());
        logisticOrderDO.setContent(placeLogisticOrderDTO.getContent());
        logisticOrderDAO.save(logisticOrderDO);

        // 3.mock申请配送员
        SendOutDTO sendOutDTO = new SendOutDTO();
        sendOutDTO.setOrderId(param.getOrderId());
        sendOutDTO.setLogisticsCode(logisticOrderDO.getLogisticCode());
        sendOutDTO.setDelivererName("test-delivererName");
        sendOutDTO.setDelivererNo("test-delivererNo");
        sendOutDTO.setDelivererPhone("13711111111");
        return sendOutDTO;
    }


    @Override
    public void cancelSendOut(String orderId) {
        // 1.查询物流单
        List<LogisticOrderDO> logisticOrderDOList = logisticOrderDAO.listByOrderId(orderId);
        // 2.移除物流单
        if (CollectionUtils.isNotEmpty(logisticOrderDOList)) {
            logisticOrderDAO.cancelPickGoods(orderId, SendOutStatusEnum.CANCEL.getCode());
        }
    }


    /**
     * 调用三方物流系统，下物流单子单
     * @author xuyou
     * 2022/7/31 0031 22:47
     * @param param
     */
    private PlaceLogisticOrderDTO thirdPartyLogisticApi(SendOutParam param) {
        // 模拟调用了第三方物流系统
        String logisticCode = RandomUtil.genRandomNumber(11);
        String content = "测试物流单内容";
        return new PlaceLogisticOrderDTO(logisticCode,content);
    }

}
